package yanc.app

import grails.converters.JSON
import org.slf4j.Logger
import org.slf4j.LoggerFactory

import javax.servlet.http.HttpServletResponse

class VersionController {
    def versionService
    static final Logger logger = LoggerFactory.getLogger(VersionController.class)

    def getAll() {
        def data = [:]
        def page = Integer.parseInt("${params.page ?: 1}")
        def pagesize = Integer.parseInt("${params.pagesize ?: 20}")
        def list = Version.list(max: pagesize, offset: (page - 1) * pagesize, sort: "id", order: "desc")
        def length = Version.count()
        if (list) {
            data << [statuCode: "0", errMsg: "0", data: list, total: length]
        } else {
            data << [statuCode: "1", errMsg: "1"]
        }
        render data as JSON
    }

    def get() {
        def logoImg = request.getFile("file")
        def filePath = request.getSession().getServletContext().getRealPath("apk")
        File f = new File(filePath)
        if (!f.exists()) {
            f.mkdirs()
        }
        def logoName = logoImg.getOriginalFilename()
        def fileSuffix = logoName.substring(logoName.lastIndexOf("."))
        def fileName = "${new Date().format("yyyyMMddHHmmss")}${fileSuffix}"
        def file = new File("${filePath}/${fileName}")
        logoImg.transferTo(file)
        render fileName
    }

    def download() {
        def versions = Version.list([sort: "id", order: "desc", max: 1])
        if (versions.size() != 0) {
            def version = versions.get(0)
            def apkFileName = version.fileName
            def apkFilePath = request.getSession().getServletContext().getRealPath("apk")
            def apkFile = new File("${apkFilePath}/${apkFileName}")
            def inputStream
            try {
                long apkFileSize = apkFile.size()
                response.reset()
                response.setCharacterEncoding("utf-8")
                response.setContentType("application/x-download")
                response.setHeader("Accept-Ranges", "bytes")
                response.setHeader("Content-Length", "${apkFileSize}")
                response.setHeader("Content-Disposition", "attachment;filename=\"${new String(apkFileName.getBytes("utf-8"), "iso-8859-1")}\"")

                inputStream = new FileInputStream(apkFile.getPath())
                long position = 0
                if (null != request.getHeader("Range")) {
                    response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT)
                    try {
                        position = Long.parseLong(request.getHeader("Range").replaceAll("bytes=", "").replaceAll("-", ""))
                    } catch (NumberFormatException e) {
                        position = 0
                        e.printStackTrace()
                    }
                }

                def outputStream = response.getOutputStream()
                response.setHeader("Content-Range", "bytes ${position}-${apkFileSize - 1}/${apkFileSize}")
                inputStream.skip(position)

                byte[] buffer = new byte[10240]
                int length
                while ((length = inputStream.read(buffer, 0, buffer.length)) != -1) {
                    outputStream.write(buffer, 0, length)
                }
                outputStream.flush()
            } finally {
                if (inputStream != null) {
                    inputStream.close()
                }
//                if(outputStream !=null){
//                    outputStream.close()
//                }
            }
        }
    }

    def filedownload() {
        def versions = Version.list([sort: "id", order: "desc", max: 1])
        if (versions.size() != 0) {
            def version = versions.get(0)
            def apkFileName = version.fileName
            def apkFilePath = request.getSession().getServletContext().getRealPath("apk")
            def apkFile = new File("${apkFilePath}/${apkFileName}")
            BufferedOutputStream bos = null
            BufferedInputStream bis = null
            try {
                long apkFileSize = apkFile.size()

                response.setHeader("Content-disposition", "attachment; filename=" + apkFileName)
                response.contentType = "application/x-rarx-rar-compressed"
                response.setHeader("Content-Length", "${apkFileSize}")

                bos = new BufferedOutputStream(response.outputStream)
                bis = new BufferedInputStream(new FileInputStream(apkFile))
                byte[] buffer = new byte[1024]
                int len = -1
                while ((len = bis.read(buffer)) != -1) {
                    bos.write(buffer, 0, len)
                    bos.flush()
                }
                bos.flush()
            } catch (Exception e) {
                logger.error(e.getLocalizedMessage())
            } finally {
                if (bis != null) {
                    bis.close()
                }
                if (bos != null) {
                    bos.close()
                }
            }
        }
    }

    def add() {
        def data = [:]
        def page = Integer.parseInt("${params.page ?: 1}")
        def pagesize = Integer.parseInt("${params.pagesize ?: 20}")
        def version = new Version()
        bindData(version, params, [exclude: ['page', 'pagesize']])
        if (Version.findByVersionId(version.versionId)) {
            data << [statuCode: "1", errMsg: "0"]
        } else {
            versionService.add(version)
            def list = Version.list(max: pagesize, offset: (page - 1) * pagesize, sort: "id", order: "desc")
            def length = Version.count()
            data << [statuCode: "0", errMsg: "0", data: list, total: length]
        }
        render data as JSON
    }

    def del() {
        def data = [:]
        def page = Integer.parseInt("${params.page ?: 1}")
        def pagesize = Integer.parseInt("${params.pagesize ?: 20}")
        def id = Integer.parseInt("${params.id ?: ''}")
        versionService.del(id)
        def list = Version.list(max: pagesize, offset: (page - 1) * pagesize, sort: "id", order: "desc")
        def length = Version.count()
        data << [statuCode: "0", errMsg: "0", data: list, total: length]
        render data as JSON
    }

    def refresh() {
        def data = [:]
        def page = Integer.parseInt("${params.page ?: 1}")
        def pagesize = Integer.parseInt("${params.pagesize ?: 20}")
        def id = Integer.parseInt("${params.id ?: ''}")
//        def versionId = "${params.versionId}"
        try {
//            def versions = Version.findByVersionId(versionId)
//            if (versions) {
//                data << [statuCode: "1", errMsg: "1"]
//            } else {
            def version = Version.findById(id)
            bindData(version, params, [exclude: ['page', 'pagesize', 'id']])
            versionService.update(version)
            def list = Version.list(max: pagesize, offset: (page - 1) * pagesize, sort: "id", order: "desc")
            def length = Version.count()
            data << [statuCode: "0", errMsg: "0", data: list, total: length]
//            }
            render data as JSON
        } catch (Exception e) {
            logger.error("VersionController refresh Exception" + e.message)
        }
    }
}
